<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>设计模式——享元模式</title>
    <script type="application/javascript" charset="utf-8" src="../../common/CommonUtils.js"></script>
    <script type="application/javascript" charset="utf-8">
        // 利用享元模式优化 design_flyweight_01.html 的代码

        var Car = function (make, model, year) {
            this.make = make;
            this.model = model;
            this.year = year;
        };
        Car.prototype = {
            constructor : Car,
            getMake : function () {
                return this.make;
            },
            getModel : function () {
                return this.model;
            },
            getYear : function () {
                return this.year;
            }
        };

        // 工厂模式（闭包工厂）对静态数据进行封装
        var CarFactory = (function () {
            // 用于存放创建的汽车
            var createCars = [];
            return {
                createCar : function (make, model, year) {
                    if (createCars[make+model+year]) {
                        return createCars[make+model+year];
                    } else {
                        var car = new Car(make, model, year);
                        createCars[make+model+year] = car;
                        return car;
                    }
                }
            };
        })();

        // 单体模式（闭包单体）将内在数据和外在数据结合在一起
        var CarRecordManager = (function () {
            // 存放已经登记好的汽车
            var carRecordDataBase = {};
            return {
                addCarRecord : function (make, model, year,owner,tag,renewDate) {
                    var car = CarFactory.createCar(make, model, year);
                    carRecordDataBase[tag] = {
                        car : car,
                        owner : owner,
                        tag : tag,
                        renewDate : renewDate
                    };
                },
                renewDateRegistration : function (tag,newRenewDate) {
                    carRecordDataBase[tag].renewDate = newRenewDate;
                }
            };
        })();

        // 通过享元模式优化代码后，构造5百万辆车，大概用时 766ms,web内存消耗大概是:180
        // 可以明显的看出，节省了浏览器的内存占用
        var stime = new Date().getTime();
        var arr = [];
        for (var i = 0; i < 5000000; i++) {
            //arr.push(new Car('上海大众','迈腾','2014-01-01','wl','甘A8888','2015-01-01'));
            arr.push(CarRecordManager.addCarRecord('上海大众','迈腾','2014-01-01','wl','甘A8888','2015-01-01'));
        }
        var etime = new Date().getTime();
        alert(etime - stime);
    </script>
</head>
<body>

</body>
</html>